package com.digital.welcome.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.digital.welcome.entity.RolePermission;
import com.digital.welcome.mapper.PermissionMapper;
import com.digital.welcome.mapper.RolerPermissionMapper;
import com.digital.welcome.response.Result;
import com.digital.welcome.service.RolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolerPermissionMapper, RolePermission> implements RolePermissionService {

    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public String setPermissionByRoleId(Integer roleId, List<String> list) {
        for (String permissionName : list) {
            Integer permissionId = permissionMapper.getPermissionIdByPermission(permissionName);
            try {
                boolean res = permissionMapper.insertRolePermission(roleId, permissionId);
            } catch (Exception e) {
                continue;
            }

        }
        List<String> list1 = permissionMapper.selectAllPermissionNameByRoleId(roleId);
        List<String> compare = compare(list, list1);
        try {
            for (String permissionName : compare) {
                Integer permissionId = permissionMapper.getPermissionIdByPermission(permissionName);
                permissionMapper.deletePermissionByPermissionIdAndRoleId(permissionId, roleId);
            }
        } catch (Exception e) {
            return JSON.toJSONString(new Result<>().setCode(0).setMessage("无修改"));
        }
        return JSON.toJSONString(new Result<>().setCode(0).setMessage("修改成功"));
    }


    public List<String> compare(List<String> list1, List<String> list2) {
        Map<String, Integer> map = new HashMap<String, Integer>(list1.size() + list2.size());
        List<String> diff = new ArrayList<String>();
        List<String> maxList = list1;
        List<String> minList = list2;
        if (list2.size() > list1.size()) {
            maxList = list2;
            minList = list1;
        }

        for (String string : maxList) {
            map.put(string, 1);
        }

        for (String string : minList) {
            Integer cc = map.get(string);
            if (cc != null) {
                map.put(string, ++cc);
                continue;
            }
            map.put(string, 1);
        }

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if (entry.getValue() == 1) {
                diff.add(entry.getKey());
            }
        }
        return diff;

    }
}
